package com.dingwei.superiordiary.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.dingwei.superiordiary.R;
import com.dingwei.superiordiary.adapter.adapter.SizeAdapter;
import com.dingwei.superiordiary.adapter.adapter.TypeAdapter;
import com.dingwei.superiordiary.app.MyApplication;
import com.dingwei.superiordiary.bean.CommodityDetailsBean;
import com.dingwei.superiordiary.mvp.presenter.EditOrderPresenter;
import com.dingwei.superiordiary.mvp.view.Contract;
import com.library.flowlayout.FlowLayoutManager;
import com.library.flowlayout.NestedRecyclerView;
import com.library.flowlayout.SpaceItemDecoration;
import com.lihao.baselibrary.base.BaseActivity;
import com.lihao.baselibrary.utils.DisplayUtil;
import com.lihao.baselibrary.utils.GlideRoundTransform;
import com.lihao.baselibrary.utils.MathUtil;
import com.lihao.baselibrary.weight.TitleBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created time 2018/2/26.
 * Creator 南柯一梦丶 on
 * Personal signature 余生还长 何必慌张
 * Page description :
 */

public class EditOrderActivity extends BaseActivity implements Contract.EditOrderView {

    EditOrderPresenter editOrderPresenter = new EditOrderPresenter(this);

    @Bind(R.id.title_bar)
    TitleBar titleBar;
    @Bind(R.id.img)
    ImageView img;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_info)
    TextView tvInfo;
    @Bind(R.id.type_RecyclerView)
    NestedRecyclerView typeRecyclerView;
    @Bind(R.id.size_RecyclerView)
    NestedRecyclerView sizeRecyclerView;
    @Bind(R.id.img_reduce)
    ImageView imgReduce;
    @Bind(R.id.tv_num)
    TextView tvNum;
    @Bind(R.id.img_add)
    ImageView imgAdd;
    @Bind(R.id.tv_price)
    TextView tvPrice;
    @Bind(R.id.tv_prompt)
    TextView tvPrompt;
    @Bind(R.id.btn_pay)
    SuperButton btnPay;
    @Bind(R.id.data_layout)
    LinearLayout dataLayout;
    @Bind(R.id.type_layout)
    LinearLayout typeLayout;
    @Bind(R.id.size_layout)
    LinearLayout sizeLayout;
    private String id;
    private CommodityDetailsBean bean;

    int num = 1;

    public static RequestOptions options;

    private TypeAdapter typeAdapter;
    private SizeAdapter sizeAdapter;

    private double price;
    private int stock;

    private String typeId = "";
    private String sizeId = "";

    private String typeStr = "";
    private String sizeStr = "";


    @Override
    protected int getContentViewId() {
        return R.layout.activity_edit_order;
    }

    @Override
    protected void initData() {

        Glide.with(BaseActivity.context)
                .load(bean.data.icon)
                .apply(MyApplication.options)
                .into(img);
        tvTitle.setText(bean.data.name);
        String freight = "";
        if (bean.data.freight == 0) {
            freight = "免运费";
        } else {
            freight = "运费" + bean.data.freight + "元";
        }
        String stock = "";
        if (this.stock == 0) {
            stock = "没有库存";
        } else if (this.stock >= 0) {
            stock = "库存充足";
        } else {
            stock = "仅剩" + stock;
        }
        tvInfo.setText(freight + " | " + stock);
        tvPrice.setText("￥" + MathUtil.trimShu(price + ""));


        FlowLayoutManager flowLayoutManager = new FlowLayoutManager();
        //设置每一个item间距
        typeRecyclerView.addItemDecoration(new SpaceItemDecoration(DisplayUtil.dip2px(BaseActivity.context, 8)));
        typeRecyclerView.setLayoutManager(flowLayoutManager);
        typeAdapter = new TypeAdapter(BaseActivity.context);
        typeRecyclerView.setAdapter(typeAdapter);


        FlowLayoutManager flowLayoutManager1 = new FlowLayoutManager();
        //设置每一个item间距
        sizeRecyclerView.addItemDecoration(new SpaceItemDecoration(DisplayUtil.dip2px(BaseActivity.context, 8)));
        sizeRecyclerView.setLayoutManager(flowLayoutManager1);
        sizeAdapter = new SizeAdapter(BaseActivity.context);
        sizeRecyclerView.setAdapter(sizeAdapter);


        if (bean.data.option == null || bean.data.option.size() == 0) {
            typeLayout.setVisibility(View.GONE);
            sizeLayout.setVisibility(View.GONE);
        } else {
            typeLayout.setVisibility(View.VISIBLE);
            sizeLayout.setVisibility(View.VISIBLE);

            typeAdapter.addAll(bean.data.option);
            CommodityDetailsBean.DataBean.OptionBeanX optionBeanX = bean.data.option.get(0);
            optionBeanX.isSelect = true;
            typeId = optionBeanX.id;
            typeStr = optionBeanX.label;
            typeAdapter.notifyItemChanged(0, optionBeanX);
            sizeAdapter.addAll(bean.data.option.get(0).option);

        }


        typeAdapter.setOnTypeInterFace(new TypeAdapter.onTypeInterFace() {
            @Override
            public void setSize(int position) {

                for (int i = 0; i < typeAdapter.getAllData().size(); i++) {
                    CommodityDetailsBean.DataBean.OptionBeanX optionBeanX = typeAdapter.getItem(i);
                    optionBeanX.isSelect = false;
                    for (int i1 = 0; i1 < optionBeanX.option.size(); i1++) {
                        CommodityDetailsBean.DataBean.OptionBeanX.OptionBean optionBean = optionBeanX.option.get(i1);
                        optionBean.isSelect = false;
                    }
                }

                CommodityDetailsBean.DataBean.OptionBeanX optionBeanX = typeAdapter.getItem(position);
                optionBeanX.isSelect = true;

                typeAdapter.notifyDataSetChanged();

                typeId = optionBeanX.id;
                typeStr = optionBeanX.label;
                sizeId = "";
                sizeStr = "";
                sizeAdapter.clear();
                sizeAdapter.addAll(optionBeanX.option);
            }
        });

        sizeAdapter.setOnSizeInterFaceListener(new SizeAdapter.onSizeInterFace() {
            @Override
            public void check(int position) {
                for (int i = 0; i < sizeAdapter.getAllData().size(); i++) {
                    CommodityDetailsBean.DataBean.OptionBeanX.OptionBean optionBean = sizeAdapter.getItem(i);
                    optionBean.isSelect = false;
                }
                CommodityDetailsBean.DataBean.OptionBeanX.OptionBean optionBean = sizeAdapter.getItem(position);
                optionBean.isSelect = true;

                sizeAdapter.notifyDataSetChanged();
                sizeId = optionBean.id;
                sizeStr = optionBean.name;
                setPrice(optionBean);
            }
        });


    }

    public void setPrice(CommodityDetailsBean.DataBean.OptionBeanX.OptionBean option) {
        tvPrice.setText("￥" + MathUtil.trimShu(option.price + ""));
        String freight = "";
        if (bean.data.freight == 0) {
            freight = "免运费";
        } else {
            freight = "运费" + bean.data.freight + "元";
        }
        String stock = "";
        if (option.quantity == 0) {
            stock = "没有库存";
        } else if (option.quantity >= 0) {
            stock = "库存充足";
        } else {
            stock = "仅剩" + stock;
        }
        tvInfo.setText(freight + " | " + stock);
        this.stock = option.quantity;
        this.price = option.price;
        num = 1;
        tvNum.setText(num + "");
    }

    @Override
    protected void initView() {
        id = getIntent().getStringExtra("id");
        bean = (CommodityDetailsBean) getIntent().getSerializableExtra("bean");
        options = new RequestOptions()
                .centerCrop()
                .placeholder(R.drawable.ic_default)
                .error(R.drawable.ic_default)
                .transform(new GlideRoundTransform(getApplicationContext(), 8))
                .diskCacheStrategy(DiskCacheStrategy.NONE);

        stock = bean.data.stock;
        price = bean.data.price;

    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.img_reduce, R.id.img_add, R.id.btn_pay, R.id.btn_add_shopcart})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_reduce:
                num = num - 1;
                if (stock > 0) {
                    if (num == 0) {
                        num = 1;
                    }
                } else {
                    num = 0;
                }
                tvNum.setText(num + "");

                break;
            case R.id.img_add:

                num = num + 1;
                if (num > stock) {
                    num = stock;
                    showToast("不能大于库存");
                }

                tvNum.setText(num + "");
                break;
            case R.id.btn_pay:
                if (bean.data.option != null && bean.data.option.size() > 0) {
                    if (TextUtils.isEmpty(typeId) || TextUtils.isEmpty(sizeId)) {
                        showToast("请选择商品规格");
                        return;
                    }
                }
                if (stock == 0) {
                    showToast("库存为0，请重新选择");
                    return;
                }
                intent = new Intent(BaseActivity.context, FirmOrderActivity.class);
                intent.putExtra("bean", bean.data);
                intent.putExtra("id", id);
                intent.putExtra("isShare", getIntent().getBooleanExtra("isShare", false));
                intent.putExtra("key", getIntent().getStringExtra("key"));
                intent.putExtra("num", num);
                if (bean.data.option != null && bean.data.option.size() > 0) {
                    intent.putExtra("attribute", typeId + "," + sizeId);
                    intent.putExtra("attributeStr", typeStr + "(" + sizeStr + ")");
                    intent.putExtra("price", price);
                    intent.putExtra("stock", stock);
                }
                startActivity(intent);
                break;
            case R.id.btn_add_shopcart:
                if (bean.data.option != null && bean.data.option.size() > 0) {
                    if (TextUtils.isEmpty(typeId) || TextUtils.isEmpty(sizeId)) {
                        showToast("请选择商品规格");
                        return;
                    }
                }
                if (stock == 0) {
                    showToast("库存为0，请重新选择");
                    return;
                }
                String option="";
                if (bean.data.option != null && bean.data.option.size() > 0){
                    for (CommodityDetailsBean.DataBean.OptionBeanX optionBeanX : bean.data.option) {
                        if (optionBeanX.isSelect){
                            for (CommodityDetailsBean.DataBean.OptionBeanX.OptionBean optionBean : optionBeanX.option) {
                                if (optionBean.isSelect){
                                    option = "[\""+optionBeanX.label+"\",\""+optionBean.name+"\"]";
                                    break;
                                }
                            }
                        }
                    }
                }
                editOrderPresenter.addShopCart(id,option,num);
                break;
        }
    }
}
